package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.user.AdminConstans;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.feign.WemediaFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Date;

@Service
@Transactional
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 按照状态分页查询用户列表
     *
     * @param dto
     * @return
     */

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //参数判断
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //构建分页参数
        IPage<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> iPage = page(page, wrapper);

        //封装结果集
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal());
        responseResult.setData(iPage.getRecords());
        return responseResult;
    }

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 根据状态进行审核
     *
     * @param dto
     * @param status
     * @return
     */
    @Override
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //参数检查
        if (dto.getId() == null || dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查status
        if (status == null || (!status.equals(AdminConstans.FAIL_AUTH)) && (!status.equals(AdminConstans.PASS_AUTH))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //修改审核状态
        ApUserRealname apUserRealname = new ApUserRealname();

        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if (dto.getMsg() != null && dto.getMsg().length() > 0) {
            apUserRealname.setReason(dto.getMsg());
        }

        LambdaUpdateWrapper<ApUserRealname> wrapper=new LambdaUpdateWrapper<>();
        wrapper.eq(ApUserRealname::getId,dto.getId());
        wrapper.set(ApUserRealname::getStatus,status);
        update(wrapper);

        //审核通过的话,注册为自媒体人,作者
        if (status.equals(AdminConstans.PASS_AUTH)) {
            ResponseResult responseResult = this.createWmUserAndAuthor(dto);
            if (responseResult != null) {
                return responseResult;
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }

    //注册为自媒体人和作者
    private ResponseResult createWmUserAndAuthor(AuthDto dto) {
        //获取ap_user的信息
        ApUserRealname userRealname = getById(dto.getId());
        //获取用户id
        Integer userId = userRealname.getUserId();
        ApUser apUser = this.apUserMapper.selectById(userId);
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            //封装自媒体人信息
            wmUser.setApUserId(apUser.getId());
            wmUser.setApAuthorId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(AdminConstans.PASS_AUTH.intValue());
            this.wemediaFeign.save(wmUser);
        }
        Integer apAuthorId = wmUser.getApAuthorId();

        //判断是否存在apAuthor
        Integer apUserId = wmUser.getApUserId();
        ApAuthor apAuthor = this.articleFeign.findByUserId(apAuthorId);
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(apUserId);
            apAuthor.setType(AdminConstans.AUTH_TYPE);
            articleFeign.save(apAuthor);
        }
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);
        return null;
    }
}
